package com.micolor.logr.runtime.component;

import com.micolor.logr.runtime.component.enumcomponent.EnumClassInvokeComponent;
import com.micolor.logr.runtime.component.enumcomponent.EnumCacheInvokeComponent;
import com.micolor.logr.runtime.entity.LogFieldEnum;
import com.micolor.logr.runtime.interfaces.LogFieldEnumInitInterface;
import com.micolor.logr.runtime.properties.LogREnum;
import com.micolor.logr.runtime.properties.LogREnumsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author EvanGe
 * @Type EnumDataComponent.java
 * @Desc
 * @date 2024/7/8 16:26
 */
@Component
@Slf4j
public class EnumDataComponent {

    @Autowired
    EnumClassInvokeComponent enumClassInvokeComponent;
    @Autowired
    EnumCacheInvokeComponent enumCacheInvokeComponent;
    @Autowired
    private LogREnumsProperties logREnumsProperties;

    /**
     * 根据反射类的名称执行反射类的getLogFieldEnum方法，并返回结果
     *
     * @param enumName 字典名称
     * @param enumTypeOrParam 字典类型
     * @throws ClassNotFoundException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws RuntimeException
     */
    public List<LogFieldEnum> getEnumObject(String enumName,Object enumTypeOrParam) throws
            ClassNotFoundException,
            NoSuchMethodException,
            InvocationTargetException,
            IllegalAccessException,
            RuntimeException {
        List<LogFieldEnum> logFieldEnums = new ArrayList<>();
        List<LogREnum> logREnums = logREnumsProperties.getEnums();
        LogREnum logREnum = logREnums.stream().filter(e -> e.getName().equals(enumName)).findFirst().orElse(null);

        if(logREnum==null) {
            log.error("字典配置{}没有找到配置文件内容",enumName);
            return logFieldEnums;
        }
        if(!logREnum.isEnable()){
            log.warn("字典配置{}的enable设置为false,程序不做获取数据操作",enumName);
            return logFieldEnums;
        }

        if(logREnum.getLoadType().equals("CLASS_BASED")){
            //从类执行的方式加载
            log.debug("{}从类{}加载,参数: {} ",enumName,logREnum.getInitCls(),enumTypeOrParam);
            return enumClassInvokeComponent.getEnumObject(logREnum.getInitCls(),enumTypeOrParam);
        }else if(logREnum.getLoadType().equals("CACHE_BASED")){
            //从缓存的方式加载
        }
        return logFieldEnums;
    }
}
